#pragma once
#include "connection.hpp"
#include "Socket.hpp"
#include <memory>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <Util.hpp>
#include <Com.hpp>
#include "Log.hpp"
#include <functional>
#include "Channel.hpp"
using namespace LogMoudle;
using func_t = std::function<void(std::shared_ptr<connection>conn)>;
using namespace SocketMoule;

class Listener : public connection
{
public:
    Listener(int port, func_t func)
        : sockfd(-1),
          socket(std::make_unique<Tcpserver>(port)),
          func(func) // 补上成员初始化
    {
        sockfd = socket->getfd();
        Util::setNonBlocking(sockfd);
    }

    int getfd() override { return sockfd; }

    void Accept()override
    {
        while (true)
        {
            int client_fd = socket->Accept();
            if (client_fd == -1)
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR) // 修正 else if 写法
                    continue;
                else
                {
                    LOG(LogLevel::ERROR) << "accept error";
                    break;
                }
            }

            // 合法的fd
            std::shared_ptr<connection> conn =
            std::make_shared<Channel>(client_fd); // 隐式向上转换
            func(conn);
        }
    }

private:
    int sockfd;
    std::unique_ptr<Tcpserver> socket;
    func_t func; 
};
